import timeUtils from './timeUtil.js'

var foo = {

	// 后端服务的URL地址
	serverURL: 'http://192.168.3.8:8000/im_bird_sys/',

	// 后端netty服务的URL地址
	nettyURL: 'ws://192.168.3.8:8888/ws',

	WEBSOCKET: null,

	CONNECT: 1, // "第一次(或重连)初始化连接"),
	CHAT: 2, // "聊天消息"),
	SIGNED: 3, // "消息签收"),
	KEEPALIVE: 4, // "客户端保持心跳"),
	PULL_FRIEND: 5, // "拉取好友");

	/** 和后端的ChatMsg聊天实体保持字段一致
	 */
	ChatMsg: function(sendUserId, acceptUserId, msg, id) {
		this.id = id
		this.msg = msg
		this.sendUserId = sendUserId
		this.acceptUserId = acceptUserId
	},

	/**消息对象
	 */
	DataContent: function(action, chatMsg, extand) {
		this.action = action
		this.chatMsg = chatMsg
		this.extand = extand
	},

	/**
	 * 字符串非空判断
	 */
	isNotNull: (str) => {
		if (str != undefined && str != null && str != '') {
			return true
		}
		return false
	},

	/**
	 * 存用户信息到本地缓存
	 */
	setUserGlobalInfo: (user) => {
		uni.setStorageSync('userInfo', user);
	},

	/**
	 * 生成任意长度的随机字符串，默认32位
	 */
	randomString: (length) => {
		let result = "";
		if (length == undefined || length == null || length == '') {
			length = 32
		}
		let str = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"
		for (let i = 0; i < length; i++) result += str.charAt(Math.floor(Math.random() * str.length))
		return result
	},

	/**
	 * 异步获取本地缓存
	 */
	getStorageSync: (key) => {
		const str = uni.getStorageSync(key)
		if (str != '') {
			return JSON.parse(str)
		}
		return null
	},

	/**
	 * 异步存储本地缓存
	 */
	setStorageSync: (Key, data) => {
		uni.setStorageSync(Key, JSON.stringify(data))
	},

	/**
	 * 把用户A<-->朋友B之间的聊天记录做本地缓存
	 */
	saveChatHistory: (userId, friendId, msg, time, flag) => {

		var chatId = 'chat_' + userId + "_" + friendId; // 用户A<-->朋友B 聊天记录的 key

		// 判断本地缓存是否存有二者的聊天记录
		var chatHistoryList = uni.getStorageSync(chatId) // 一个字符串形式的数组

		if (chatHistoryList != '') {
			chatHistoryList = JSON.parse(chatHistoryList)
		} else {
			chatHistoryList = [] // 如果为空，赋一个空的数组
		}

		// 构建聊天记录的对象 msg
		// 0: user 为发送方
		// 1. friend 为发送方
		var unitChatHistory = function(userId, friendId, msg, time, flag) {
			this.sendUserId = flag == 0 ? userId : friendId
			this.acceptUserId = flag == 0 ? friendId : userId
			this.msg = msg
			this.time = time
		}

		// 向 Array 中追加 msg 对象
		chatHistoryList.push(new unitChatHistory(userId, friendId, msg, time, flag));

		// 重新将用户A<-->朋友B聊天记录，写入本地缓存
		uni.setStorageSync(chatId, JSON.stringify(chatHistoryList))
	},

	/**
	 * 获取 用户A<-->朋友B 聊天记录
	 */
	getChatHistory: (userId, friendId) => {

		var chatId = 'chat_' + userId + "_" + friendId; // 用户A<-->朋友B 聊天记录的 key

		// 判断本地缓存是否存有二者的聊天记录
		var chatHistoryList = uni.getStorageSync(chatId) // 一个字符串形式的数组
		if (chatHistoryList != '') {
			chatHistoryList = JSON.parse(chatHistoryList)
		} else {
			chatHistoryList = [] // 如果为空，赋一个空的数组
		}

		return chatHistoryList
	},
	
	/**
	 * 从本地缓存中，移除与某位好友的聊天记录
	 * @param {Object} userId
	 * @param {Object} friendId
	 */
	delChatHistory(userId, friendId) {
		var chatId = 'chat_' + userId + "_" + friendId; // 用户A<-->朋友B 聊天记录的 key
		
		uni.removeStorageSync(chatId);
	},

	/**
	 * 聊天记录快照:保存了与朋友聊天的最后一条消息
	 */
	saveChatSnapShot: (userId, friendUserId, msg, isRead, time) => {

		var snapshotId = 'chat_snapshot' + userId;

		var chatSnapshotList = uni.getStorageSync(snapshotId) // 一个字符串形式的数组

		if (chatSnapshotList != '') {
			chatSnapshotList = JSON.parse(chatSnapshotList)
			// 循环快照List,并且判断每个元素是否包含friendUserId,如果匹配
			// 则删除该用户快照
			chatSnapshotList.some(item => {
				if (item.friendUserId == friendUserId) {
					var index = chatSnapshotList.indexOf(item)
					chatSnapshotList.splice(index, 1)
					return true
				}
			})
		} else {
			chatSnapshotList = [] // 如果为空，赋一个空的数组
		}

		// 构建聊天快照对象
		var unitChatHistory = function(userId, friendUserId, msg, isRead, time) {
			this.userId = userId
			this.friendUserId = friendUserId
			this.msg = msg
			this.isRead = isRead
			this.time = time
		}

		// 将聊天快照对象添加到首位置
		chatSnapshotList.unshift(new unitChatHistory(userId, friendUserId, msg, isRead, time));

		// 写入本地缓存
		uni.setStorageSync(snapshotId, JSON.stringify(chatSnapshotList))

	},

	/**
	 * 获取某用户的所有聊天快照
	 */
	getChatSnapShot: (userId) => {
		var snapshotId = 'chat_snapshot' + userId;

		var chatSnapshotList = uni.getStorageSync(snapshotId)

		if (chatSnapshotList != '') {
			chatSnapshotList = JSON.parse(chatSnapshotList)
		} else {
			chatSnapshotList = [] // 如果为空，赋一个空的数组
		}

		return chatSnapshotList
	},

	/**
	 * 更改和某个用户地聊条快照为已读
	 */
	ReadSnapChatShot: (userId, friendUserId) => {
		var snapshotId = 'chat_snapshot' + userId;

		var chatSnapshotList = JSON.parse(uni.getStorageSync(snapshotId))
		
		try {
			chatSnapshotList.forEach(item => {
				//跳出条件
				if (item.friendUserId == friendUserId) {
					item.isRead = true
					throw new Error("LoopTerminates");
				}
			});
		} catch (e) {}
		
		// 重新存储
		uni.setStorageSync(snapshotId,JSON.stringify(chatSnapshotList))
	},
	
	/**
	 * 删除用户与某好友的聊天快照
	 */
	delSnapChatShot(userId, friendUserId) {
		var snapshotId = 'chat_snapshot' + userId;
		
		var chatSnapshotList = JSON.parse(uni.getStorageSync(snapshotId))
		
		var newArr = chatSnapshotList.filter(item => item.friendUserId != friendUserId) // 过滤掉friendUserId的记录
		
		// 重新存储
		uni.setStorageSync(snapshotId,JSON.stringify(newArr))
	},

	/**
	 * 拿到用户聊天快照中未读的快照数量
	 */
	getChatSnapShotNotReadCount: (userId) => {
		var snapshotId = 'chat_snapshot' + userId;
		var chatSnapshotList = uni.getStorageSync(snapshotId)

		if (chatSnapshotList != '') {
			chatSnapshotList = JSON.parse(chatSnapshotList)
		} else {
			chatSnapshotList = [] // 如果为空，赋一个空的数组
		}

		let count = 0
		chatSnapshotList.forEach(item => {
			if (!item.isRead) count = count + 1
		})
		return count
	},

	emptyChatSnapShot(userId, friendUserId) {
		var snapshotId = 'chat_snapshot' + userId;
		var chatSnapshotList = uni.getStorageSync(snapshotId) // 一个字符串形式的数组
		
		if (chatSnapshotList != '') {
			chatSnapshotList = JSON.parse(chatSnapshotList)

			chatSnapshotList.some(item => {
				if (item.friendUserId == friendUserId) {
					item.msg = ''
					return true
				}
			})
		} else {
			chatSnapshotList = [] // 如果为空，赋一个空的数组
		}
		
		// 重新写入本地缓存
		uni.setStorageSync(snapshotId, JSON.stringify(chatSnapshotList))
	},

	/**
	 * 保存联系人列表
	 */
	setContactList: (myFriendList) => {
		var contactListStr = JSON.stringify(myFriendList)
		uni.setStorageSync('contactList', contactListStr)
	},

	/**
	 * 获取联系人列表
	 */
	getContactList: () => {
		var contactListStr = uni.getStorageSync('contactList')
		if (contactListStr != '') {
			return []
		}
		return JSON.parse(contactListStr)
	},

	/**
	 * 根据联系人id,获取联系人信息
	 */
	getFriendInfoFromContactList: (friendUserId) => {
		var contactListStr = uni.getStorageSync('contactList')
		var targetFriend = null
		if (contactListStr != '') {
			var contactList = JSON.parse(contactListStr)

			try {
				contactList.forEach(friend => {
					//跳出条件
					if (friend.friendUserId == friendUserId) {
						targetFriend = friend
						throw new Error("LoopTerminates");
					}
				});
			} catch (e) {}
			return targetFriend
		}
		return targetFriend
	},

	/**
	 * 发送通知
	 */
	sendToast: (msg) => {
		uni.showToast({
			title: msg,
			duration: 2000,
			icon: 'none'
		});
	},

	/**
	 * 获取当前时间
	 */
	getNowDate: () => {
		var date = new Date();
		var seperator1 = "-";
		var seperator2 = ":";
		var month = date.getMonth() + 1;
		var strDate = date.getDate();
		var strHour = date.getHours();
		var strMinute = date.getMinutes();
		var strSecond = date.getSeconds();
		if (month >= 1 && month <= 9) {
			month = "0" + month;
		}
		if (strDate >= 0 && strDate <= 9) {
			strDate = "0" + strDate;
		}
		if (strHour >= 0 && strHour <= 9) {
			strHour = "0" + strHour
		}
		if (strMinute >= 0 && strMinute <= 9) {
			strMinute = "0" + strMinute
		}
		if (strSecond >= 0 && strSecond <= 9) {
			strSecond = "0" + strSecond
		}
		var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate + " " + strHour +
			seperator2 + strMinute + seperator2 + strSecond;
		return currentdate;
	},

	/**
	 * 聊天快照条目展示的时间
	 */
	snapTimeFormat: (str) => {
		var foo = timeUtils.dateFormat(str)
		// 比较两个时间的大小
		if (timeUtils.compareDate(new Date(), foo)) {
			var date = new Date();
			var seperator1 = "-";
			var seperator2 = ":";
			var month = date.getMonth() + 1;
			var strDate = date.getDate();
			var strHour = date.getHours();
			var strMinute = date.getMinutes();
			var strSecond = date.getSeconds();
			if (month >= 1 && month <= 9) {
				month = "0" + month;
			}
			if (strDate >= 0 && strDate <= 9) {
				strDate = "0" + strDate;
			}
			if (strHour >= 0 && strHour <= 9) {
				strHour = "0" + strHour
			}
			if (strMinute >= 0 && strMinute <= 9) {
				strMinute = "0" + strMinute
			}
			if (strSecond >= 0 && strSecond <= 9) {
				strSecond = "0" + strSecond
			}
			var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate + " " + strHour +
				seperator2 + strMinute + seperator2 + strSecond;
			return currentdate;
		} else {
			return foo.getHours() + ":" + foo.getMinutes()
		}
	}
}
export default foo
